<template>
  <div class="common-charts-container">
    <div class="common-charts-item">
      <canvas
        id="canvas"
        height="300"
        width="300"
        class="effect-container"
      ></canvas>
      <div class="bottom-title">
        <span class="card-tag">行星运转</span>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";

@Component({})
export default class Canvas extends Vue {
  mounted() {
    this.init();
  }

  sun = new Image();
  moon = new Image();
  earth = new Image();
  init() {
    this.sun.src = "https://mdn.mozillademos.org/files/1456/Canvas_sun.png";
    this.moon.src = "https://mdn.mozillademos.org/files/1443/Canvas_moon.png";
    this.earth.src = "https://mdn.mozillademos.org/files/1429/Canvas_earth.png";
    window.requestAnimationFrame(this.drawCanvasForOne);
  }
  drawCanvasForOne() {
    // 使用类型断言
    let ctx: any = (document.getElementById("canvas") as any).getContext("2d");

    ctx.globalCompositeOperation = "destination-over";
    ctx.clearRect(0, 0, 300, 300); // clear canvas

    ctx.fillStyle = "rgba(0,0,0,0.4)";
    ctx.strokeStyle = "rgba(0,153,255,0.4)";
    ctx.save();
    ctx.translate(150, 150);

    // Earth
    let time = new Date();
    ctx.rotate(
      ((2 * Math.PI) / 60) * time.getSeconds() +
        ((2 * Math.PI) / 60000) * time.getMilliseconds()
    );
    ctx.translate(105, 0);
    ctx.fillRect(0, -12, 50, 24); // Shadow
    ctx.drawImage(this.earth, -12, -12);

    // Moon
    ctx.save();
    ctx.rotate(
      ((2 * Math.PI) / 6) * time.getSeconds() +
        ((2 * Math.PI) / 6000) * time.getMilliseconds()
    );
    ctx.translate(0, 28.5);
    ctx.drawImage(this.moon, -3.5, -3.5);
    ctx.restore();

    ctx.restore();

    ctx.beginPath();
    ctx.arc(150, 150, 105, 0, Math.PI * 2, false); // Earth orbit
    ctx.stroke();

    ctx.drawImage(this.sun, 0, 0, 300, 300);

    window.requestAnimationFrame(this.drawCanvasForOne);
  }
}
</script>
